﻿using JMcms.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace JMcms.Web.UI
{
    public class FtpUpload
    {

        string FileSaveUri = string.Empty;
        //FTP用户名密码，就是本机的用户名密码
        string ftpUser = string.Empty;
        string ftpPassWord = string.Empty;
        string chushifile = string.Empty;
        public FtpUpload(string ftpUser, string ftpPassWord, string chushifile, string domainname)
        {
            FileSaveUri = "ftp://" + domainname;
            this.ftpUser = ftpUser;
            this.ftpPassWord = DESEncrypt.Decrypt(ftpPassWord);
            this.chushifile = chushifile;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="binData">文件流数组</param>
        /// <param name="key">文件名</param>
        /// <param name="result">result</param>
        /// <returns></returns>
        public bool FtpUploadFile(byte[] binData, string key, string customDmain, out string result)
        {


            try
            {
                #region 创建目录开始
                //格式化为URI
                Uri uri = new Uri(FileSaveUri + "/" + chushifile + "/");
                //检测目录是否存在

                if (!DirectoryIsExist(uri, ftpUser, ftpPassWord))
                {
                    //创建目录
                    uri = new Uri(FileSaveUri + "/" + chushifile);
                    if (CreateDirectory(uri, ftpUser, ftpPassWord))
                    {
                        //检测下一级目录是否存在
                        uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/");
                        if (!DirectoryIsExist(uri, ftpUser, ftpPassWord))
                        {
                            //创建目录
                            uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym());
                            if (CreateDirectory(uri, ftpUser, ftpPassWord))
                            {

                                //检测下一级目录是否存在
                                uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/" + d() + "/");
                                if (!DirectoryIsExist(uri, ftpUser, ftpPassWord))
                                {
                                    //创建目录
                                    uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/" + d());
                                    if (CreateDirectory(uri, ftpUser, ftpPassWord))
                                    {
                                        //return true;
                                    }
                                    else
                                    { //XtraMessageBox.Show("创建目录：{0}失败", FileCategory); return false; 
                                    }
                                }
                                else
                                {
                                    //return true;
                                }
                            }
                            else
                            { //XtraMessageBox.Show("创建目录：{0}失败", FileCategory); return false; 
                            }
                        }
                        else
                        {
                            //return true; //检测下一级目录是否存在
                            uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/" + d() + "/");
                            if (!DirectoryIsExist(uri, ftpUser, ftpPassWord))
                            {
                                //创建目录
                                uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/" + d());
                                if (CreateDirectory(uri, ftpUser, ftpPassWord))
                                {
                                    //return true;
                                }
                                else
                                { //XtraMessageBox.Show("创建目录：{0}失败", FileCategory); return false; 
                                }
                            }
                            else
                            {
                                //return true;
                            }

                        }
                    }
                    else
                    {
                        //XtraMessageBox.Show("创建目录：{0}失败", FileSource); return false;
                    }
                }
                else
                {
                    //检测下一级目录是否存在
                    uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/");
                    if (!DirectoryIsExist(uri, ftpUser, ftpPassWord))
                    {
                        //创建目录
                        uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym());
                        if (CreateDirectory(uri, ftpUser, ftpPassWord))
                        {
                            //检测下一级目录是否存在
                            uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/" + d() + "/");
                            if (!DirectoryIsExist(uri, ftpUser, ftpPassWord))
                            {
                                //创建目录
                                uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/" + d());
                                if (CreateDirectory(uri, ftpUser, ftpPassWord))
                                {
                                    //return true;
                                }
                                else
                                { //XtraMessageBox.Show("创建目录：{0}失败", FileCategory); return false; 
                                }
                            }
                            else
                            {
                                //return true;
                            }
                        }
                        else
                        { //XtraMessageBox.Show("创建目录：{0}失败", FileCategory); return false;
                        }
                    }
                    else
                    {
                        //检测下一级目录是否存在
                        uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/" + d() + "/");
                        if (!DirectoryIsExist(uri, ftpUser, ftpPassWord))
                        {
                            //创建目录
                            uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/" + d());
                            if (CreateDirectory(uri, ftpUser, ftpPassWord))
                            {
                                //return true;
                            }
                            else
                            { //XtraMessageBox.Show("创建目录：{0}失败", FileCategory); return false; 
                            }
                        }
                        else
                        {
                            //return true;
                        }
                        //return true;
                    }
                }
                #endregion 创建目录结束
                string url = "/" + chushifile + "/" + ym() + "/" + d() + "/" + Path.GetFileName(key);
                //string newThumbnailPath = "/" + chushifile + "/" + ym() + "/" + d() + "/" + Path.GetFileName(newThumbnailFileName);
                uri = new Uri(FileSaveUri + "/" + chushifile + "/" + ym() + "/" + d() + "/" + Path.GetFileName(key));
                FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);//创建FtpWebRequest实例uploadRequest
                uploadRequest.Proxy = null;
                uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;//将FtpWebRequest属性设置为上传文件
                uploadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);//认证FTP用户名密码
                using (Stream requestStream = uploadRequest.GetRequestStream())//获得用于上传FTP的流
                {
                    requestStream.Write(binData, 0, binData.Length);//将buffer写入流
                   

                }
                
                using (FtpWebResponse uploadResponse = (FtpWebResponse)uploadRequest.GetResponse())//返回FTP服务器响应，上传完成
                {
                    string zhuangtai = uploadResponse.StatusDescription;
                }
                if (string.IsNullOrEmpty(customDmain))
                {
                    result = customDmain + "/" + url.TrimStart('/'); //默认网址
                }
                else
                {
                    result = customDmain.TrimEnd('/') + "/" + url.TrimStart('/'); //自定义网址
                }

                
                return true;
            }
            catch (Exception e)
            {
                //写日志
                Log.Debug("文件上传失败：", e);
                result = e.Message;
                return false;
               
            }
            finally
            {
              
            }



         
        }

        /// <summary>
        /// ftp创建目录(创建文件夹)
        /// </summary>
        /// <param name="IP">IP服务地址</param>
        /// <param name="UserName">登陆账号</param>
        /// <param name="UserPass">密码</param>
        /// <param name="FileSource"></param>
        /// <param name="FileCategory"></param>
        /// <returns></returns>
        private static bool CreateDirectory(Uri IP, string UserName, string UserPass)
        {
            try
            {
                FtpWebRequest FTP = (FtpWebRequest)FtpWebRequest.Create(IP);
                FTP.Credentials = new NetworkCredential(UserName, UserPass);
                FTP.Proxy = null;
                FTP.KeepAlive = false;
                FTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                FTP.UseBinary = true;
                FtpWebResponse response = FTP.GetResponse() as FtpWebResponse;
                response.Close();
               
                return true;
            }
            catch (Exception ex)
            {
                //写日志
                Log.Debug("ftp创建文件夹目录失败：", ex);
                return false;
            }
            
        }
        /// <summary>
        /// 检测目录是否存在
        /// </summary>
        /// <param name="pFtpServerIP"></param>
        /// <param name="pFtpUserID"></param>
        /// <param name="pFtpPW"></param>
        /// <returns>false不存在，true存在</returns>
        private static bool DirectoryIsExist(Uri pFtpServerIP, string pFtpUserID, string pFtpPW)
        {
            string[] value = GetFileList(pFtpServerIP, pFtpUserID, pFtpPW);
            if (value == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public static string[] GetFileList(Uri pFtpServerIP, string pFtpUserID, string pFtpPW)
        {
            StringBuilder result = new StringBuilder();
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(pFtpServerIP);
                reqFTP.Proxy = null;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(pFtpUserID, pFtpPW);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch(Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 返回上传年月
        /// </summary>
        /// <param name="fileName">上传文件名</param>
        private string ym()
        {
            string path = DateTime.Now.ToString("yyyyMM");
            return path;
        }
        /// <summary>
        /// 返回上传r
        /// </summary>
        /// <param name="fileName">上传文件名</param>
        private string d()
        {
            string path = DateTime.Now.ToString("dd");
            return path;
        }
       
    }

}

